<?php
namespace app\index\controller;

use think\Db;

class Index extends Common
{
    public static $CARNIVAL_DAYS = 5;
    public static $CURRENT_DAY = 1;


    public function index()
    {
        //查询我的预约
        $reservation = Db::name('reservation')->where('user_id', $_SESSION['user_id'])->select();
        $this->assign('reservation', $reservation);
        return $this->fetch();
    }

    public function cancel(){
        $id = input('id');
        $auth = Db::name('reservation')->where('id', $id)->delete();
        if($auth){
            $this->success('success!');
        }else{
            $this->error('error');
        }

    }

    public function new_reservation()
    {
        $available_day = [];
        for ($i = 1; $i <= self::$CARNIVAL_DAYS; $i++) {
            $available_day[] = 'day ' . $i;
        }
        for ($i = 1; $i <= self::$CURRENT_DAY; $i++) {
            unset($available_day[0]);
        }

        $this->assign('CARNIVAL_DAYS', self::$CARNIVAL_DAYS);
        $this->assign('CARNIVAL_DAYS', self::$CURRENT_DAY);
        $this->assign('available_day', $available_day);
        return $this->fetch();
    }

    public function save_reservation(){
        $day = input('day');
        $invitation_code = $this->random_str(6);

        $data = ['day'=>$day, 'invitation_code'=>$invitation_code];
        $data['user_id'] = $_SESSION['user_id'];
        $data['user_name'] = $_SESSION['user_name'];
        $data['status'] = 'created';
        $data['created_at'] = date('Y-m-d H:i:s');

        //一个用户在5天内最多可以预约3次，
        $user_count = Db::name('reservation')->where('user_id', $data['user_id'])->count();
        if($user_count >= 3){
            $this->error('One user can have AT MOST 3 reservations in total in the 5 days');
        }
        //每天只能预订一次
        $user_count2 = Db::name('reservation')
            ->where('user_id', $data['user_id'])
            ->where('day', $data['day'])
            ->count();
        if($user_count2 >= 1){
            $this->error('One user can have ONLY 1 reservation per day');
        }
        //在这5天内，我们最多允许10人预订
        $user_count3 = Db::name('reservation')
            ->count();
        if($user_count3 >= 10){
            $this->error('we allow 10 reservations at maximum');
        }

        $auth = Db::name('reservation')->insertGetId($data);
        if($auth){
            $this->success('success!', 'index');
        }else{
            $this->error('error');
        }

    }

    public function random_str($length) {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyz';
        $str = '';
        for($i = 0; $i < $length; $i++)
        {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}


